package com.moli.iov.down.command.codec.encode.data;

import com.moli.iov.down.model.dto.remoting.CommandDto;
import com.moli.iov.down.model.dto.remoting.extend.CommandExtendDto;
import com.moli.iov.down.command.design.command.param.setting.SettingDataEncoderCommand;
import com.moli.iov.down.command.design.factory.param.SettingEncoderFactory;
import com.moli.iov.util.NumberUtil;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;

/**
 * <p>
 *  终端参数设置  0xD9
 * </p>
 *
 * @author: zql
 * @Date: 2018/11/28 10:29
 */
public class ParameterSettingDataEncoder extends BaseEncoder implements DataEncoder {


    @Override
    public byte[] encode(CommandDto commandDto) {
        byte[] all = getByteBuf(commandDto);

        //查询参数总数 n
        all = ArrayUtils.addAll(all, NumberUtil.intToHexToByte(commandDto.getCommandExtendDtos().size(), 2));

        //参数内容列表
        byte[] params = this.encodeParameterContent(commandDto.getCommandExtendDtos());

        return ArrayUtils.addAll(all, params);
    }

    /**
     * 组装参数内容
     * @param commandExtendDtos
     * @return
     */
    private byte[] encodeParameterContent(List<CommandExtendDto> commandExtendDtos){

        byte[] all = new byte[0];

        for(CommandExtendDto commandExtendDto : commandExtendDtos){

            SettingDataEncoderCommand settingDataEncoderCommand =
                    SettingEncoderFactory.getSettingDataEncoderCommand(commandExtendDto.getParameterId());
            all = settingDataEncoderCommand.execute(commandExtendDto, all);
        }

        return all;
    }
}
